// packageA/pages/cashService/operator/login/login.js
const {
  imgPath
} = require('../../../../utils/request')
const {
  request
} = require('../../../../utils/request');
const {
  hexMD5
} = require('../../../../utils/md5');
const {
  encryptSM2
} = require('../../../../utils/sm-crypto');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgPath: imgPath,
    captchaData: {},
    loginMode: 2, // 1 账号登录 2密码登录
    idNum: '',  //202309整改，字段含义改为操作员账号
    phone: '',
    captcha: '',
    smsCaptcha: '',

    btnText: '获取验证码',
    btnDisable: false,
    timeout: 0,
    username: '',
    password: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '操作员登录'
    })
    this.fetchCaptcha()
  },
  onShow: function () {
    if (wx.getStorageSync('userInfo').loginType == 1) {
      wx.setStorageSync('checkStationFlag', true)
      wx.redirectTo({
        url: '/pages/cashService/operator/operator',
      })
    }
  },

  /**
   * 获取图片验证码
   */
  fetchCaptcha() {
    request('/smsk/wechat/auth/captchaw150h30', 'GET').then(res => {
      this.setData({
        captchaData: res.data.data,
      })
    })
  },

  /**
   * 获取短信验证码
   */
  fetchSmsCaptcha() {
    // 校验表单
    if (!this.validForm()) {
      return
    }
    // 拼装参数
    let query = {
      idNum: this.data.idNum,
      phone: this.data.phone,
      captchaId: this.data.captchaData.captchaId,
      captcha: this.data.captcha
    }
    request('/smsk/wechat/auth/sms', 'POST', query).then(res => {
      console.log(res.data)
      if (res.data.code == 0) {
        wx.showToast({
          title: '短信发送成功',
          icon: 'success'
        })
        this.setData({
          btnDisable: true,
          timeout: 60
        })
        this.btnCountDown()
      } else {
        this.showToast(res.data.message)
        this.fetchCaptcha()
      }
    })
  },
  /**
   * 修改短信发送按钮状态
   */
  btnCountDown() {
    if (this.data.timeout === 0) {
      this.setData({
        btnDisable: false,
        btnText: '获取验证码'
      })
    } else {
      this.setData({
        btnText: '重新发送(' + this.data.timeout + ')'
      })
      setTimeout(() => {
        this.setData({
          timeout: this.data.timeout - 1,
        })
        this.btnCountDown()
      }, 1000)
    }
  },

  /**
   * 点击“立即绑定”
   */
  login() {
    // 表单校验
    if (!this.validForm('login')) {
      return
    }
    // 防止重复点击登录
    if (this.data.loginDisable) {
      return
    }
    this.setData({
      loginDisable: true
    })
    if (this.data.loginMode === 1) {
      // 拼装参数
      let loginData = {
        idNum: this.data.idNum,
        phone: this.data.phone,
        captcha: this.data.captcha,
        captchaId: this.data.captchaData.captchaId,
        smsCaptcha: this.data.smsCaptcha
      }
      wx.showLoading({
        title: '登录中',
      })
      console.log(loginData)
      request('/smsk/wechat/auth/optlogin', 'POST', loginData).then(res => {
        console.log(res.data)
        wx.hideLoading()
        this.setData({
          loginDisable: false
        })
        let that = this
        if (res.data.code == 0) {
          wx.setStorageSync('token', res.data.data.token)
          wx.setStorageSync('userInfo', res.data.data)
          wx.setStorageSync('checkStationFlag', true)
          if (res.data.data.loginType == 1) { //站点操作员
            wx.redirectTo({
              url: '/pages/cashService/operator/operator',
            })
          } else if (res.data.data.loginType == 4) { // 三方操作员
            wx.redirectTo({
              url: '/pages/cashService/third/list/list',
            })
          } else if (res.data.data.loginType == 5) { // 三方操作员
            wx.redirectTo({
              url: '/pages/cashService/third/list/list',
            })
          }
        } else if(res.data.code === 13) {
          wx.showModal({
            title: '提示',
            content: res.data.message,
            confirmText: "去重置",
            success (res) {
              if (res.confirm) {
                that.go2ResetPwd()
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        } else {
          this.showToast(res.data.message)
          this.fetchCaptcha()
        }
      })
    } else if (this.data.loginMode === 2) { //密码登录模式
      // 拼装参数
      let loginData = {
        username: this.data.username,
        password: encryptSM2(this.data.password, this.data.captchaData.publicKey),
        captcha: this.data.captcha,
        captchaId: this.data.captchaData.captchaId,
      }
      wx.showLoading({
        title: '登录中',
      })
      let that = this
      request('/smsk/wechat/auth/operatorlogin', 'POST', loginData).then(res => {
        console.log(res.data)
        wx.hideLoading()
        this.setData({
          loginDisable: false
        })
        if (res.data.code == 0) {
          wx.setStorageSync('token', res.data.data.token)
          wx.setStorageSync('userInfo', res.data.data)
          wx.setStorageSync('checkStationFlag', true)
          if (res.data.data.loginType == 1) { //站点操作员
            wx.redirectTo({
              url: '/pages/cashService/operator/operator',
            })
          } else if (res.data.data.loginType == 4) { // 三方操作员
            wx.redirectTo({
              url: '/pages/cashService/third/list/list',
            })
          } else if (res.data.data.loginType == 5) { // 三方操作员
            wx.redirectTo({
              url: '/pages/cashService/third/list/list',
            })
          }
        } else if(res.data.code === 13) {
          wx.showModal({
            title: '提示',
            content: res.data.message,
            confirmText: "去重置",
            success (res) {
              if (res.confirm) {
                that.go2ResetPwd()
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        } else {
          this.showToast(res.data.message)
          this.fetchCaptcha()
        }
      })
    }
  },
  /**
   * 表单校验
   */
  validForm(str) {
    if (this.data.loginMode === 1) {
      // 202309整改：去除身份证校验，改为账号登陆
      // if (!this.data.idNum || !(/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(this.data.idNum))) {
      //   this.showToast('请填写正确的证件号')
      //   return false
      // }
      if (!this.data.idNum) {
        this.showToast('请填写操作员账号')
        return false
      }
      if (!this.data.phone || !(/^1[345789]\d{9}$/.test(this.data.phone))) {
        this.showToast('请填写正确的手机号')
        return false
      }
      if (!this.data.captcha || !(this.data.captchaData.hashCode == hexMD5(this.data.captcha.toUpperCase()))) {
        this.showToast('请填写正确的图片验证码')
        return false
      }
      if (str == 'login') {
        if (!this.data.smsCaptcha) {
          this.showToast('请填写正确的短信验证码')
          return false
        }
      }
      return true
    } else if (this.data.loginMode === 2) {
      if (!this.data.username) {
        this.showToast('请填写操作员账号')
        return false
      }
      if (!this.data.password) {
        this.showToast('请填写密码')
        return false
      }
      if (!this.data.captcha || !(this.data.captchaData.hashCode == hexMD5(this.data.captcha.toUpperCase()))) {
        this.showToast('请填写正确的图片验证码')
        return false
      }
      return true
    }
  },

  /**
   * 简化弹出
   */
  showToast(msg) {
    wx.showToast({
      title: msg,
      icon: 'none'
    })
  },
  /**
   * 切换登录模式
   */
  toggleLoginMode() {
    if (this.data.loginMode === 1) {
      this.setData({
        loginMode: 2
      });
    } else {
      this.setData({
        loginMode: 1
      });
    }
  },
  go2ResetPwd(){
    wx.navigateTo({
      url: '/pages/cashService/resetPwd/index',
    })
  }
})